package com.securecrt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.sshbot.R;
import org.sshbot.TerminalView;
import org.sshbot.transport.SSH;
import org.sshbot.transport.Transport;
import org.sshbot.util.Utils;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.securecrt.pojo.CKRemPass;
import com.securecrt.pojo.SQLLanguage;
import com.securecrt.pojo.SaveSessionAdapter;
import com.securecrt.pojo.Savesession;
import com.securecrt.pojo.SQLHelper;
import com.securecrt.pojo.Settings;
import com.securecrt.pojo.Settings_Main;

import de.mud.terminal.VT320;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.LayoutInflater.Factory;
import android.util.AttributeSet;
import android.view.InflateException;
import android.view.LayoutInflater;


public class SaveSession extends Activity implements OnClickListener{

	ArrayList<Savesession> list=new ArrayList<Savesession>();
	List<Settings> setting_pro=new ArrayList<Settings>();
	List<Settings_Main> set_main=new ArrayList<Settings_Main>();
	List<CKRemPass> ck_rempass=new ArrayList<CKRemPass>();
	SQLHelper eventsData;
	SQLLanguage sslang;

	ListView listSaveSession;
	String host,port, user,pass, mac, cipher;
	Button btBack, btHome,btNewConnect;
	private boolean checked=false;
	private String ckrempass="uncheck";
	int idRadio=1;

    ProgressDialog pro;
    private Transport transport;
    
    public static boolean isPortrait = true;
    private int bgChange;
    private int fontsize=12;
    Background[] bground;
    Background[] flag;
	private String idlang="";
	String idl="";
	AlertDialog alertDialog_;
	AlertDialog.Builder builder;
	int idbg=0;
	private SSH sh;
	TerminalView tv;
	private Long idSession=0l;
	private String sendcheck="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.savesession);
		super.onCreate(savedInstanceState);
		dataProcess();
		checkExistListSaveSession();
		loadList();
		loadVersion();
		settingProcess();
		loadImageBackground();
		loadImageFlagLanguage();
		changuageLang();
		loadSettingMain();
	}

	private void loadSettingMain(){
		set_main=eventsData.getSettingsMain();
		if(set_main!=null){
			for(int i=0;i<set_main.size();i++){
				setIdl(set_main.get(i).getLanguage());
				setBgChange(Integer.parseInt(set_main.get(i).getBackground()));
				setActivityBackgroundColor(getBgChange());
			}
		}else{
			setActivityBackgroundColor(getBgChange());
			return;
		}
	}
	private void settingMain(){
		if(eventsData.deleteSettingMainAll())
			eventsData.insertSettingMain(getIdbg(), getIdl());
	}
	@Override
	protected void onPause() {
		changuageLang();
		super.onPause();
	}
	@Override
	protected void onResume() {
		changuageLang();
		super.onResume();
	}

	private void changuageLang(){
		String lang=getIdl();
		Locale locale=new Locale(lang);
        Locale.setDefault(locale);
        Configuration config=new Configuration();
        config.locale=locale;
        getBaseContext().getResources().updateConfiguration(config, 
        		getBaseContext().getResources().getDisplayMetrics());
    }
	
	private void loadVersion(){
		final TextView infoPro=(TextView)findViewById(R.id.infoPro);
		try {
			infoPro.setText(" "+this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	private void dataProcess(){
		eventsData=new SQLHelper(this);
        Cursor cursor=getEvents();
        showEvents(cursor);
	}

	private void checkExistListSaveSession(){
		if(list.size()<1){
			addNewConnection();
		}
	}
	//////////////////////////////////////////
	private void loadImageBackground() {
		final int arr_img[]={R.drawable.bg1,R.drawable.bg2,R.drawable.bg3,R.drawable.bg4,R.drawable.bg5};
		final int[] bg={R.string.bg1,R.string.bg2,R.string.bg3,R.string.bg4,R.string.bg5};
		bground = new Background[arr_img.length];
		for(int i=0;i<arr_img.length;i++){
			bground[i]=new Background(getString(bg[i]), getImg(arr_img[i]),getId(arr_img[i]));
		}
	}
	private void loadImageFlagLanguage(){
		final int arr_img[]={R.drawable.vn,R.drawable.uk,R.drawable.korea};
		final int[] nameflag={R.string.flagvn,R.string.flaguk,R.string.flagkr};
		flag = new Background[arr_img.length];
		for(int i=0;i<arr_img.length;i++){
			flag[i]=new Background(getString(nameflag[i]), getImg(arr_img[i]),getId(arr_img[i]));
		}
	}
	private int getId(int res){
		return res;
	}
	private Drawable getImg(int res){
		Drawable img=getResources().getDrawable(res);
		img.setBounds(0, 0, 48, 48);
		return img;
	}
	
	private void loadList(){
        listSaveSession=(ListView)findViewById(R.id.listSaveSession);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
        int[] colors = {0, 0xFFFF0000, 0};
        listSaveSession.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
        listSaveSession.setDividerHeight(1);
        listSaveSession.setOnItemClickListener(LoginServerAuto);
	}
	
	private void settingProcess(){
		Bundle receivecolor=SaveSession.this.getIntent().getExtras();
		if(receivecolor==null){
			return;
		}else if(receivecolor.getInt("idcolor")==0){
			setBgChange(R.drawable.bg1);
			setActivityBackgroundColor(getBgChange());
		}
		else if(receivecolor!=null){
			setBgChange(receivecolor.getInt("idcolor"));
			setActivityBackgroundColor(getBgChange());
			setFontsize(receivecolor.getInt("fontsize"));
			setIdl(receivecolor.getString("idl"));
			changuageLang();
		}
	}

	public void setActivityBackgroundColor(int color) {
		Resources res = getResources();
		setBgChange(color);
		Drawable drawable = res.getDrawable(color);
		LinearLayout setting_theme =   (LinearLayout)findViewById(R.id.layoutSavesession); 
		setting_theme.setBackgroundDrawable(drawable);
	}
	
	private View callAlertDialog(int layout,int idbgLayout){
		Context mContext=getApplicationContext();
		LayoutInflater inflater=(LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout1=inflater.inflate(layout, (ViewGroup) findViewById(idbgLayout));
		return layout1;
	}
	
	private void spinnerBackground(){
		ListAdapter adapter = new AnimalAdapter( this, bground );
		builder=new AlertDialog.Builder(this);
		builder.setTitle("Select background");
		builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getApplicationContext(), bground[which].getName(), Toast.LENGTH_SHORT).show();
			    setIdbg(bground[which].get_id());
				dialog.dismiss();
			}
		});
		alertDialog_=builder.create();
		alertDialog_.show();
	}
	
	private int spinnerFontsize(){
		final String[] font_size={"20 px","22 px","24 px","26 px"};
		builder=new AlertDialog.Builder(this);
		builder.setTitle("Select fontsize");
		builder.setSingleChoiceItems(font_size, -1, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		        Toast.makeText(getApplicationContext(), font_size[item], Toast.LENGTH_SHORT).show();
				String item1=font_size[item];
				String[] fs=item1.trim().split(" ");
				fontsize=Integer.parseInt(fs[0].toString());
				alertDialog_.dismiss();
		    }
		});

		alertDialog_=builder.create();
		
		alertDialog_.show();return fontsize;
	}
	private void spinnerLanguage(){

		ListAdapter adapter = new AnimalAdapter( this, flag );
		builder=new AlertDialog.Builder(this);
		builder.setTitle("Select flag");
		builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(getApplicationContext(), flag[which].getName(), Toast.LENGTH_SHORT).show();
				idlang=flag[which].getName();
				dialog.dismiss();
			}
		});
		alertDialog_=builder.create();
		alertDialog_.show();
	}
	private void refresh() {
//		finish();
		Bundle sendcolor=new Bundle();
		sendcolor.putInt("idcolor", getBgChange());
		sendcolor.putInt("fontsize", fontsize);
		sendcolor.putString("idl", getIdl());
        Intent myIntent = new Intent(this,SaveSession.class);
        myIntent.putExtras(sendcolor);
        startActivity(myIntent);
    }
	
	private String checklanguage(){
		if(idlang.equalsIgnoreCase("Vietnam"))
			setIdl("vn");
		else if(idlang.equalsIgnoreCase("English"))
			setIdl("en");
		else if(idlang.equalsIgnoreCase("Korea"))
			setIdl("kr");
		return getIdl();
	}
	
	private void settingsClick(){
		final Dialog dialog5=new Dialog(this);
		dialog5.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog5.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		View layout=callAlertDialog(R.layout.settingalertdialog,R.id.settingalertdialog);
		dialog5.setContentView(layout);
		Button btnbackground=(Button)layout.findViewById(R.id.btnbackground);
		btnbackground.setOnClickListener(this);
		Button btnfontsize=(Button)layout.findViewById(R.id.btnfontsize);
		btnfontsize.setOnClickListener(this);
		Button btnlanguage=(Button)layout.findViewById(R.id.btnlanguage);
		btnlanguage.setOnClickListener(this);
		TextView bgtitle1=(TextView)layout.findViewById(R.id.bgtitle1);
		bgtitle1.setOnClickListener(this);
		TextView bgtitle2=(TextView)layout.findViewById(R.id.bgtitle2);
		bgtitle2.setOnClickListener(this);
		TextView fztitle1=(TextView)layout.findViewById(R.id.fztitle1);
		fztitle1.setOnClickListener(this);
		TextView fztitle2=(TextView)layout.findViewById(R.id.fztitle2);
		fztitle2.setOnClickListener(this);
		TextView ltitle1=(TextView)layout.findViewById(R.id.ltitle1);
		ltitle1.setOnClickListener(this);
		TextView ltitle2=(TextView)layout.findViewById(R.id.ltitle2);
		ltitle2.setOnClickListener(this);
		
		Button btsave=(Button)layout.findViewById(R.id.btsave);
		btsave.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		btsave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				eventClickBtSave();
				settingMain();
				refresh();
				dialog5.dismiss();
			}
		});
		final Button cancel=(Button)layout.findViewById(R.id.btcancel);
		cancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog5.dismiss();
			}
		});
		dialog5.show();
	}
	
	private boolean checkInput(int id,String host,String port,String user,String pass){
		boolean result=true;
		if(host.trim().equals("")){
			Utils.showErrorMessage(this,getString(R.string.errHost));					    		
    		return result=false;
		}
    	if(user.trim().equals("") && id!=3){
    		Utils.showErrorMessage(this,getString(R.string.errUser));					    		
    		return result=false;
		}
    	if(pass.trim().equals("") && id!=2 && id!=3){
    		Utils.showErrorMessage(this,getString(R.string.errPass));						    		
    		return result=false;
		}
    	String sPort=port.toString().trim();
    	boolean isBadPort=false;
    	int iPort=0;
    	try{
    		iPort=Integer.parseInt(sPort);
    	}
    	catch (Exception e) {
			isBadPort=true;
		}
    	if(iPort<=0||iPort>=65535){
    		isBadPort=true;
    	}
    	if(isBadPort && id!=2){
    		Utils.showErrorMessage(this,getString(R.string.errPort));					    		
    		return result=false;
    	}
    	return  result;
	}
	
	private void addNewConnection(){
		final Savesession item = new Savesession();
		final Dialog dialog1=new Dialog(this);
		dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		View layout=callAlertDialog(R.layout.newconnection,R.id.newconnection);
		dialog1.setContentView(layout);
		final EditText hostname=(EditText)layout.findViewById(R.id.hostname);
		final EditText port_=(EditText)layout.findViewById(R.id.port);
		final EditText username=(EditText)layout.findViewById(R.id.username);
		final EditText password=(EditText)layout.findViewById(R.id.password);
		
		RadioGroup radioGroup=(RadioGroup)layout.findViewById(R.id.radiogroup);
		final RadioButton radiobutton1=(RadioButton)layout.findViewById(R.id.radiobutton1);
		final RadioButton radiobutton2=(RadioButton)layout.findViewById(R.id.radiobutton2);
		final RadioButton radiobutton3=(RadioButton)layout.findViewById(R.id.radiobutton3);
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int checkedRadioButton=group.getCheckedRadioButtonId();
				switch (checkedRadioButton) {
				case R.id.radiobutton1:setIdRadio(1);
					radiobutton1.setButtonDrawable(R.drawable.rabutton1);
					radiobutton2.setButtonDrawable(R.drawable.rabutton2);
					radiobutton3.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(true);username.setEnabled(true);password.setEnabled(true);
					break;
				case R.id.radiobutton2:setIdRadio(2);
					radiobutton2.setButtonDrawable(R.drawable.rabutton1);
					radiobutton1.setButtonDrawable(R.drawable.rabutton2);
					radiobutton3.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(false);username.setEnabled(true);password.setEnabled(false);
					break;
				case R.id.radiobutton3:setIdRadio(3);
					radiobutton3.setButtonDrawable(R.drawable.rabutton1);
					radiobutton1.setButtonDrawable(R.drawable.rabutton2);
					radiobutton2.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(true);username.setEnabled(false);password.setEnabled(false);
					break;
				}
			}
		});
		final Button btsave=(Button)layout.findViewById(R.id.btsave);
		btsave.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		btsave.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!checkInput(getIdRadio(),hostname.getText().toString(),port_.getText().toString(),username.getText().toString(),password.getText().toString())){
					btsave.setBackgroundResource(R.drawable.bt_save_confirmconnection);
					return;
				}
				item.setHostname(hostname.getText().toString());
				item.setPort(port_.getText().toString());
				item.setUsername(username.getText().toString());
				item.setPassword(password.getText().toString());
				checked=true;
				showEx(item);
				setIdRadio(1);
				dialog1.dismiss();
			}
		});
		final Button cancel=(Button)layout.findViewById(R.id.btcancel);
		btsave.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		cancel.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				setIdRadio(1);
				dialog1.dismiss();
			}
		});
		dialog1.show();
	}
	private void init(){
		list.clear();
		Cursor cursor=getEvents();
        showEvents(cursor);
        SaveSessionAdapter adapter1 = new SaveSessionAdapter(this, list);
        listSaveSession.setAdapter(adapter1);
	}

	private boolean showEvents_(Cursor cursor){
		boolean ch=false;
		while(cursor.moveToNext()){
			long id =cursor.getLong(0);
			String hostname=cursor.getString(1);
			String port=cursor.getString(2);
			String username=cursor.getString(3);
			String password=cursor.getString(4);
			if(hostname.equals(host)&&port.equals(port)&&username.equals(user)&&password.equals(pass))
				return ch=true;
		}
		return ch;
	}
	private boolean checkSession(){
    	boolean ch=false;
    	Cursor cursor=getEvents();
        if(showEvents_(cursor))
        	return ch=true;
        return ch;
    }
	private String outDateCurrent(){
		String result="";
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		return result=dateFormat.format(date);
	}
	private void saveSessionActive(){
		String cuDate = outDateCurrent();
		String id=1+"";
		Long ssid=Long.parseLong(id.trim().toString());
		while(eventsData.checkExistsIDSession(ssid)){
			id=id+1+"";
			ssid=Long.parseLong(id.trim().toString());
		}
		eventsData.insertSaveSession(ssid,host, port, user, pass, cuDate);
		eventsData.insertRemPass(ssid, getCkrempass());
    }
	private void checkRememberPass(Long id){
		try{
			if(eventsData.checkExistsIDRem(id)){
				int i=eventsData.UpdateCheckRemPass(getIdSession(), getCkrempass());
			}
		}catch (Exception e) {
		}
	}
	private void ssh2LoginAuto(Savesession item) throws UnknownHostException{
		boolean res = connectToServer(item.getUsername()+"@"+item.getPassword()+"@"+item.getHostname()+"@"+item.getPort());
		if(res){
			if(checked && !checkSession()){
				saveSessionActive();
			}
		}else{
			Utils.showErrorMessage(SaveSession.this,"SSH Connect Fault.");		
			return;
		}
	}
	
	private boolean connectToServer(final String uri) throws UnknownHostException {
		if (!uri.contains("@")) {
			return false;
		}
		String[] tmp = uri.split("@");
		String username_ = tmp[0];
		String pass_ = tmp[1];System.out.println("pass ssh: "+pass);
		String host_ = tmp[2];		
		int port_ = Integer.parseInt(tmp[3]);
		
		transport = null;
		sh = null;
		try {	
			sh = new SSH(username_,pass_, host_, port_);
		} catch (JSchException e) {
			e.printStackTrace();			
		}

		if(sh.isConnected()){
			transport = sh;
		}else{
			return false;
		}

		if (transport != null) {
			tv = new TerminalView(this, transport);
			if(setting_pro!=null&&setting_pro.size()>0){
				for(int i=0;i<setting_pro.size();i++){
					tv.setFontSize(Integer.parseInt(setting_pro.get(i).getFontsize()));
					tv.setBground(Integer.parseInt(setting_pro.get(i).getBackground()));
				}
			}else
				tv.setFontSize(getFontsize());
			setContentView(tv);
		}

		return true;
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

	//	transport.disconnect();
		if (eventsData != null) {
			eventsData.close();
	    }
		if(sslang!=null)
			sslang.close();
		if(alertDialog_!=null)
			alertDialog_.dismiss();
	}

	private void checkInputRemPass(String pass){
    	if(pass.trim().equals("")){
    		Utils.showErrorMessage(this,getString(R.string.errPass));		
		}
	}
	String test="";
	private void showEx(final Savesession item){
		final Dialog dialog2=new Dialog(this);
		dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog2.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		View layout=callAlertDialog(R.layout.confirmconnection,R.id.confirmconnection);
		dialog2.setContentView(layout);
		TextView connect=(TextView) layout.findViewById(R.id.connect);
		connect.setText(item.getHostname().toString());
		final EditText password_=(EditText) layout.findViewById(R.id.password);
		if(getSendcheck().equals("uncheck")){
			item.setPassword(test);
			pass=item.getPassword().toString();
		}
		else if(getSendcheck().equals("checked")||checked){
			password_.setText(item.getPassword().toString());
			pass=item.getPassword().toString();
		}
		
		host=item.getHostname().toString();
		port=item.getPort().toString();
		user=item.getUsername().toString();
		final Button cancel=(Button)layout.findViewById(R.id.cancel);
		cancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		cancel.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog2.dismiss();
			}
		});
		final Button delete=(Button)layout.findViewById(R.id.delete);
		delete.setBackgroundDrawable(getResources().getDrawable(R.drawable.bteditstatus));
		delete.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				SQLiteDatabase db=eventsData.getWritableDatabase();
				db.delete(SQLHelper.SESSION, SQLHelper.SESSION_ID + "=" +item.getId(), null);
				init();
				dialog2.dismiss();				
			}
		});
		final Button btconnect=(Button)layout.findViewById(R.id.btconnect);
		btconnect.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		btconnect.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					test=password_.getText().toString().trim();
					if(getSendcheck().equals("uncheck")){
						if(test.equals(""))
							checkInputRemPass(test);
						else{
							item.setPassword(test);
							ssh2LoginAuto(item);
						}
					}else
						ssh2LoginAuto(item);
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				dialog2.dismiss();
			}
		});
		final Button edit=(Button)layout.findViewById(R.id.edit);
		edit.setBackgroundDrawable(getResources().getDrawable(R.drawable.bteditstatus));
		edit.setOnClickListener(new Button.OnClickListener() {			
			@Override
			public void onClick(View v) {
				dialogEdit(item);
				dialog2.dismiss();				
			}
		});
		final CheckBox save_session=(CheckBox)layout.findViewById(R.id.save_session);
		if(getSendcheck().equals("checked"))
			save_session.setButtonDrawable(R.drawable.check_confirmconnection);
		else if(getSendcheck().equals("uncheck"))
			save_session.setButtonDrawable(R.drawable.checkbox_confirmconnection);
        save_session.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(buttonView.isChecked()){
					save_session.setButtonDrawable(R.drawable.check_confirmconnection);
					setCkrempass("checked");
					checkRememberPass(item.getId());
				}else{
					save_session.setButtonDrawable(R.drawable.checkbox_confirmconnection);
					setCkrempass("uncheck");
					checkRememberPass(item.getId());
				}
			}
		});
		dialog2.show();
	}
	private void dialogEdit(final Savesession item){
		final Dialog dialog3=new Dialog(this);
		dialog3.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog3.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		View layout=callAlertDialog(R.layout.editconnection,R.id.editconnection);
		dialog3.setContentView(layout);
		final EditText hostname=(EditText)layout.findViewById(R.id.hostname);
		final EditText port_=(EditText)layout.findViewById(R.id.port);
		final EditText username=(EditText)layout.findViewById(R.id.username);
		final EditText password=(EditText)layout.findViewById(R.id.password);
		
		hostname.setText(item.getHostname().toString());
		port_.setText(item.getPort().toString());
		username.setText(item.getUsername().toString());
		
		RadioGroup radioGroup=(RadioGroup)layout.findViewById(R.id.radiogroup);
		final RadioButton radiobutton1=(RadioButton)layout.findViewById(R.id.radiobutton1);
		final RadioButton radiobutton2=(RadioButton)layout.findViewById(R.id.radiobutton2);
		final RadioButton radiobutton3=(RadioButton)layout.findViewById(R.id.radiobutton3);
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int checkedRadioButton=group.getCheckedRadioButtonId();
				switch (checkedRadioButton) {
				case R.id.radiobutton1:
					radiobutton1.setButtonDrawable(R.drawable.rabutton1);
					radiobutton2.setButtonDrawable(R.drawable.rabutton2);
					radiobutton3.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(true);username.setEnabled(true);password.setEnabled(true);
					break;
				case R.id.radiobutton2:
					radiobutton2.setButtonDrawable(R.drawable.rabutton1);
					radiobutton1.setButtonDrawable(R.drawable.rabutton2);
					radiobutton3.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(false);username.setEnabled(true);password.setEnabled(false);
					break;
				case R.id.radiobutton3:
					radiobutton3.setButtonDrawable(R.drawable.rabutton1);
					radiobutton1.setButtonDrawable(R.drawable.rabutton2);
					radiobutton2.setButtonDrawable(R.drawable.rabutton2);
					port_.setEnabled(true);username.setEnabled(false);password.setEnabled(false);
					break;
				}
			}
		});
		final Button btsave=(Button)layout.findViewById(R.id.btsave);
		btsave.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		btsave.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				item.setHostname(hostname.getText().toString());
				item.setPort(port_.getText().toString());
				item.setUsername(username.getText().toString());
				item.setPassword(password.getText().toString());
				showEx(item);
				dialog3.dismiss();
			}
		});
		final Button cancel=(Button)layout.findViewById(R.id.btcancel);
		cancel.setBackgroundDrawable(getResources().getDrawable(R.drawable.btokstatus));
		cancel.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog3.dismiss();
			}
		});
		dialog3.show();
	}

	private void checkRemPass(Long item){
		String ck=eventsData.getCKRemByID(item);
		setSendcheck(ck);
	}
	private OnItemClickListener LoginServerAuto=new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
			Savesession item=(Savesession)list.get(position);
			setIdSession(item.getId());
			setting_pro=eventsData.getSettings(getIdSession());
			checkRemPass(item.getId());
			showEx(item);
		}
	};

	private Cursor getEvents(){
		SQLiteDatabase db=eventsData.getReadableDatabase();
		Cursor cursor=db.query(SQLHelper.SESSION, null, null, null, null,null, null);
		startManagingCursor(cursor);
		return cursor;
	}

	private void showEvents(Cursor cursor){
		StringBuilder ret=new StringBuilder("Saved Events:\n\n");
		while(cursor.moveToNext()){
			long id =cursor.getLong(0);
			String hostname=cursor.getString(1);
			String port=cursor.getString(2);
			String username=cursor.getString(3);
			String password=cursor.getString(4);
			String time_=cursor.getString(5);
			Savesession ss=new Savesession();
			ss.setId(id);
			ss.setHostname(hostname);
			ss.setPort(port);
			ss.setUsername(username);
			ss.setPassword(password);
			ss.setTime_(time_);
			list.add(ss);
		}
	}
	public int getIdRadio() {
		return idRadio;
	}
	public void setIdRadio(int idRadio) {
		this.idRadio = idRadio;
	}

	public int getBgChange() {
		return bgChange;
	}

	public void setBgChange(int bgChange) {
		this.bgChange = bgChange;
	}

	public int getFontsize() {
		return fontsize;
	}

	public void setFontsize(int fontsize) {
		this.fontsize = fontsize;
	}

	public String getIdl() {
		return idl;
	}

	public void setIdl(String idl) {
		this.idl = idl;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    getMenuInflater().inflate(R.menu.menu_first, menu);
	    menu.setQwertyMode(false);
	    return true;
	}
	
	private void onShowKeyboard(){
		builder=new AlertDialog.Builder(tv.getContext());
		final AlertDialog alertDialog;
		LayoutInflater inflater=(LayoutInflater) tv.getContext().getSystemService(tv.getContext().LAYOUT_INFLATER_SERVICE);
		View layout=inflater.inflate(R.layout.act_console, (ViewGroup) findViewById(R.id.keyboard_group));
		
		builder.setView(layout);
		alertDialog=builder.create();
		final Button button_keyboard=(Button)layout.findViewById(R.id.button_keyboard);
		button_keyboard.setOnClickListener(new Button.OnClickListener() {			
			@Override
			public void onClick(View v) {
				InputMethodManager mgr1 = (InputMethodManager) tv.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				mgr1.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);	
				alertDialog.dismiss();
			}
		});
		final Button button_ctrl=(Button)layout.findViewById(R.id.button_ctrl);
		button_ctrl.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Ctrl", Toast.LENGTH_SHORT).show();
		    	((VT320) tv.buffer).keyPressed(VT320.KEY_CONTROL, ' ', 0);
			}
		});
		final Button button_esc=(Button)layout.findViewById(R.id.button_esc);
		button_esc.setOnClickListener(new Button.OnClickListener() {			
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "Esc", Toast.LENGTH_SHORT).show();
		    	((VT320) tv.buffer).keyPressed(VT320.KEY_ESCAPE, ' ', 0);
			}
		});
		alertDialog.show();
	}
	 @Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.addconnect:
		    addNewConnection();
		    break;
	    case R.id.settings:			// menu: form setting
		    settingsClick();
		    break;
	    case R.id.bt_help:
			Toast.makeText(getApplicationContext(), "Wellcome to Eli SSH", Toast.LENGTH_SHORT).show();
			InputMethodManager mgr1 = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
			mgr1.showInputMethodPicker();	
			break;
	    case R.id.menu_setting:    //menu:terminal view setting
			settingsTerminal();
			break;  
	    case R.id.menu_keyboard:
	    	onShowKeyboard();
	    	InputMethodManager mgr = (InputMethodManager) tv.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);	
		    break;      
	    case R.id.menu_disconnect:
	    	Toast.makeText(getApplicationContext(), "Disconnect to Server", Toast.LENGTH_SHORT).show();
	    	finish();
	    	Intent myIntent = new Intent(this,SaveSession.class);
	    	startActivity(myIntent);
		    break;       
	    }
	    return super.onOptionsItemSelected(item);
	  }
	 
	 @Override
	 public boolean onPrepareOptionsMenu (Menu menu) {
	     if (tv == null || "".equals(tv)){
	    	 menu.getItem(3).setVisible(false);
	    	 menu.getItem(4).setVisible(false);	
	    	 menu.getItem(5).setVisible(false);	    	
	     }else{	    	 
	    	 menu.getItem(0).setVisible(false);
	    	 menu.getItem(1).setVisible(false);
	         menu.getItem(2).setVisible(false);	        
	         
	         menu.getItem(3).setVisible(true);
	    	 menu.getItem(4).setVisible(true);
	    	 menu.getItem(5).setVisible(true);
	    	 
	     }
	     return true;
	 }
	 
	 @Override
	  public void onOptionsMenuClosed(Menu menu) {
	    super.onOptionsMenuClosed(menu);
	    setVolumeControlStream(AudioManager.STREAM_MUSIC);
	  }
	 
	 protected void setMenuBackground() {
		    getLayoutInflater().setFactory(new Factory() {

		        @Override
		        public View onCreateView(final String name, final Context context,
		                final AttributeSet attrs) {

		            if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {

		                try { // Ask our inflater to create the view
		                    final LayoutInflater f = getLayoutInflater();
		                    final View[] view = new View[1];
		                    try {
		                        view[0] = f.createView(name, null, attrs);
		                    } catch (InflateException e) {
		                        //new Custom().hackAndroid23(name, attrs, f, view);
		                    }
		                    // Kind of apply our own background
		                    new Handler().post(new Runnable() {
		                        public void run() {
		                            view[0].setBackgroundColor(Color.DKGRAY);

		                        }
		                    });
		                    return view[0];
		                } catch (InflateException e) {
		                } catch (ClassNotFoundException e) {

		                }
		            }
		            return null;
		        }
		    });
		}
	 
	 private void settingsTerminal(){
		 	final Dialog dialog6=new Dialog(this);
			dialog6.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog6.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			View layout=callAlertDialog(R.layout.settingterminal,R.id.setting_terminal);
			dialog6.setContentView(layout);
			Button btnbackground=(Button)layout.findViewById(R.id.button_bg);
			btnbackground.setOnClickListener(this);
			Button btnfontsize=(Button)layout.findViewById(R.id.button_font);
			btnfontsize.setOnClickListener(this);
			
			TextView tit1_button_bg=(TextView)layout.findViewById(R.id.tit1_button_bg);
			tit1_button_bg.setOnClickListener(this);
			TextView tit2_button_bg=(TextView)layout.findViewById(R.id.tit2_button_bg);
			tit2_button_bg.setOnClickListener(this);
			TextView tit1_button_font=(TextView)layout.findViewById(R.id.tit1_button_font);
			tit1_button_font.setOnClickListener(this);
			TextView tit2_button_font=(TextView)layout.findViewById(R.id.tit2_button_font);
			tit2_button_font.setOnClickListener(this);
			Button btsave=(Button)layout.findViewById(R.id.button_save);
			btsave.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					savesettingterminal();
					dialog6.dismiss();
				}
			});
			Button cancel=(Button)layout.findViewById(R.id.button_cancle);
			cancel.setOnClickListener(new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog6.dismiss();
				}
			});
			dialog6.show();
		}
	 private int bg_terminal = 0;
	 private int font_terminal = 0;
	 public int getBg_terminal() {
		return bg_terminal;
	}

	public void setBg_terminal(int bg_terminal) {
		this.bg_terminal = bg_terminal;
	}

	public int getFont_terminal() {
		return font_terminal;
	}

	public void setFont_terminal(int font_terminal) {
		this.font_terminal = font_terminal;
	}

	private int checkColorTerminal(int idColor){
			final Integer[] arr_color = new Integer[] {1,2,3,4,5,6};
		 int id=0;
		 id=arr_color[idColor];
		 return id;
	 }
	 private void terminalBackground(){
			ListAdapter adapter = new AnimalAdapter( this, bground );
			builder=new AlertDialog.Builder(this);
			builder.setTitle("Select background");
			builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(getApplicationContext(), bground[which].getName(), Toast.LENGTH_SHORT).show();
					setBg_terminal(checkColorTerminal(which));
					alertDialog_.dismiss();dialog.cancel();
				}
			});
			alertDialog_=builder.create();
			alertDialog_.show();
		}
		private void terminalFontsize(){
			final String[] font_size={"10 px","12 px","14 px","16 px","18 px","20 px","22 px","24 px"};
			builder=new AlertDialog.Builder(this);
			builder.setTitle("Select fontsize");
			builder.setSingleChoiceItems(font_size, -1, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
			        Toast.makeText(getApplicationContext(), font_size[item], Toast.LENGTH_SHORT).show();
					String item1=font_size[item];
					String[] fs=item1.trim().split(" ");
					setFont_terminal(Integer.parseInt(fs[0].toString()));
					alertDialog_.dismiss();
			    }
			});
			alertDialog_=builder.create();
			alertDialog_.show();
			
		}
		private void eventClickBtSave(){
			String id=checklanguage();
			if(getIdbg()!=0)
				setActivityBackgroundColor(getIdbg());
			if(id=="en"||id=="kr"||id=="vn"){
				changuageLang();
			}
		}
		int fzter=0,bgter=0;
		private void savesettingterminal(){
			if(getFont_terminal() > 0){
				tv.setFontSize(getFont_terminal());
				setFzter(getFont_terminal());
			}
			if(getBg_terminal() > 0){
				tv.setBground(getBg_terminal());	
				setBgter(getBg_terminal());
			}
			tv.resetScrollPosition();
		    tv.resizeScreen();
		    if(eventsData.checkExistsID(getIdSession())){
		    	eventsData.deleteSetting(getIdSession());
			    eventsData.insertSetting(getIdSession(), bgter, fzter);
		    }else{
		    	eventsData.insertSetting(getIdSession(), bgter, fzter);
		    }
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnbackground:
					spinnerBackground();
					break;
				case R.id.bgtitle1:
					spinnerBackground();
					break;
				case R.id.bgtitle2:
					spinnerBackground();
					break;
				case R.id.btnfontsize:
					spinnerFontsize();
					break;
				case R.id.fztitle1:
					spinnerFontsize();
					break;
				case R.id.fztitle2:
					spinnerFontsize();
					break;
				case R.id.btnlanguage:
					spinnerLanguage();
					break;
				case R.id.ltitle1:
					spinnerLanguage();
					break;
				case R.id.ltitle2:
					spinnerLanguage();
					break;
				case R.id.button_bg:
					terminalBackground();
					break;
				case R.id.button_font:
					terminalFontsize();
					break;
				case R.id.tit1_button_bg:
					terminalBackground();
					break;
				case R.id.tit2_button_bg:
					terminalBackground();
					break;
				case R.id.tit1_button_font:
					terminalFontsize();
					break;
				case R.id.tit2_button_font:
					terminalFontsize();
					break;
				}
		}

		public Long getIdSession() {
			return idSession;
		}

		public void setIdSession(Long idSession) {
			this.idSession = idSession;
		}

		public int getFzter() {
			return fzter;
		}

		public void setFzter(int fzter) {
			this.fzter = fzter;
		}

		public int getBgter() {
			return bgter;
		}

		public void setBgter(int bgter) {
			this.bgter = bgter;
		}
		public int getIdbg() {
			return idbg;
		}
		public void setIdbg(int idbg) {
			this.idbg = idbg;
		}

		public String getCkrempass() {
			return ckrempass;
		}

		public void setCkrempass(String ckrempass) {
			this.ckrempass = ckrempass;
		}

		public String getSendcheck() {
			return sendcheck;
		}

		public void setSendcheck(String sendcheck) {
			this.sendcheck = sendcheck;
		}
		
}
